package com.itplh.modules.shirorealm.controller;

import com.itplh.modules.shirorealm.dao.ShiroUserDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Description:
 * @Author: tanpeng
 * @Date: 2019-07-11 18:49
 * @Version: V1.0
 */
@RestController
@RequestMapping(value = "/shirorealm")
public class LoginController {

    @Autowired
    private ShiroUserDao shiroJWTUserDao;

    @GetMapping(value = "/notLogin")
    public String notLogin() {
        return "您尚未登陆！";
    }

    @GetMapping(value = "/notRole")
    public String notRole() {
        return "您没有权限！";
    }

    @GetMapping(value = "/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        //注销
        subject.logout();
        return "成功注销！";
    }

    /**
     * 登陆
     *
     * @param username 用户名
     * @param password 密码
     */
    @PostMapping(value = "/login")
    public String login(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 执行认证登陆
        subject.login(token);
        //根据权限，指定返回数据
        String role = shiroJWTUserDao.getRole(username);
        if ("user".equals(role)) {
            return "欢迎登陆";
        }
        if ("admin".equals(role)) {
            return "欢迎来到管理员页面";
        }
        return "权限错误！";
    }
}
